package com.serverdemo.core.net;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * netty服务器的启动类
 * Created by wangqiang on 2020/4/9.
 */
public class NettyServer
{
    /**
     *socket绑定出现错误
     */
    public static final int SOCKET_BIND_ERROR = -1001;
    /**
     *socket绑定失败
     */
    public static final int SOCKET_BIND_FAILURE = -1002;

    public int boot()
    {
        NioEventLoopGroup acceptGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(acceptGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new InitHandler());

        // 监听网卡所有地址的9999端口
        try
        {
            ChannelFuture channelFuture = bootstrap.bind("0.0.0.0", 9999).sync();
            if (channelFuture.isSuccess())
            {
                return 0;
            }
            else
            {
                return SOCKET_BIND_FAILURE;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return SOCKET_BIND_ERROR;
        }

    }
}
